package com.aniljing.daemonapp.activitys

import android.content.Intent
import android.net.http.SslError
import android.os.Bundle
import android.webkit.SslErrorHandler
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.aniljing.daemonapp.R
import com.king.camera.scan.CameraScan


class MainActivity : AppCompatActivity() {
    private lateinit var webView: WebView
    private lateinit var resultLauncher: ActivityResultLauncher<Intent>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        resultLauncher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()
        ) {
            val result = it?.data?.getStringExtra(CameraScan.SCAN_RESULT)
            if (result != null) {
                webView.loadUrl(result)
            }
        }
        findViewById<Button>(R.id.toScan).setOnClickListener {
            resultLauncher.launch(Intent(this, ScanQRCodeActivity::class.java))
        }
        webView = findViewById(R.id.webView)
        // 启用 JavaScript
        // 启用 JavaScript
        val webSettings = webView.settings
        webSettings.javaScriptEnabled = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        // 确保点击网页中的链接时，仍然在 WebView 中打开
        webView.webViewClient=object :WebViewClient(){
            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                webView.reload()
            }

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                handler?.proceed() // 忽略 SSL 错误
            }
        }
    }

    override fun onResume() {
        super.onResume()
        webView.onResume()
    }
}